﻿using System;
using System.Collections;
using UnityEngine;

public class CoroutineHelper : MonoBehaviour
{
    static CoroutineHelper _instance;
    public static CoroutineHelper Instance
    {
        get
        {
            if (_instance == null)
            {
                var cortineObj = new GameObject("CoroutineHelper");
                DontDestroyOnLoad(cortineObj);
                _instance = cortineObj.AddComponent<CoroutineHelper>();
            }
            return _instance;
        }
    }

    /// <summary>
    /// 启动一个协同程序, 适用于持续进行的操作;
    /// </summary>
    /// <param name="routine">协同对象</param>
    /// <returns></returns>
    public Coroutine Begin(IEnumerator routine)
    {
        var coroutine = StartCoroutine(routine);
        return coroutine;
    }

    /// <summary>
    /// 启动一个协同程序, 适用于同步操作;
    /// </summary>
    /// <param name="act">一个Action</param>
    public void Begin(Action act)
    {
        StartCoroutine(Go(act));
    }

    IEnumerator Go(Action act)
    {
        yield return 1;
        if (act != null)
            act.Invoke();
    }
}
